<template>
    <div id="risk-table" style="height: 100%">
        <div class="table-box" :style="{ height: !msg.hidePage ? 'calc(100% - 38px)' : '100%' }">
            <vxe-table
                :auto-resize="true"
                resizable
                stripe
                :resizable-config="{ minWidth: '50' }"
                ref="riskTable"
                v-tableTop="pages.currentPage"
                @cell-click="handleRow"
                show-header-overflow="tooltip"
                :show-footer="msg.showFooter && (data.length ? true : false)"
                :footer-method="msg.footerMethod || footerMethod"
                :footer-cell-style="{ backgroundColor: '#e7f2ff', padding: '4px 0' }"
                @cell-dblclick="handleDbRow"
                @checkbox-change="handleChecked"
                @checkbox-all="handleCheckedAll"
                @sort-change="handleSort"
                @filter-change="handleFilter"
                :filter-config="{ remote: msg.localSearch ? false : true, iconNone: 'el-icon-search', iconMatch: 'el-icon-search' }"
                :sort-config="{ remote: msg.localSearch ? false : true }"
                :data="data"
                border
                style="width: 100%; height: 100%"
                size="mini"
                :key="keyIndex"
                :max-height="msg.maxHeight"
                :height="msg.height"
                :scoped-slot="labelHead"
                :cell-style="msg.cellStyle || cellStyle"
                :highlight-current-row="msg.isCurrent"
                :highlight-hover-row="msg.isHover"
            >
                <!-- 勾选 -->
                <vxe-column v-if="msg.checked.on" type="checkbox" width="60">
                    <template #header v-if="msg.checked.option">
                        <el-dropdown @command="handleCommand">
                            <span class="el-dropdown-link"><i class="el-icon-arrow-down" style="margin-left: 5px"></i></span>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="0">选择当前页</el-dropdown-item>
                                <el-dropdown-item command="1">选择所有页</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </template>
                </vxe-column>
                <vxe-column
                    v-for="item in title"
                    :fixed="item.type === 'btn' ? (item.fixed ? item.fixed : 'right') : ''"
                    :key="item.prop"
                    :width="item.width || ''"
                    :min-width="item.minWidth || ''"
                    :title="item.name"
                    :field="item.prop || item.val || ''"
                    :filters="item.filters"
                    :filter-method="item.selectSearch ? filterTypeSelect : filterHandler"
                    :filter-render="{ name: 'FilterInput' }"
                    :show-overflow-tooltip="true"
                    :sortable="item.sortable"
                    :scoped-slot="labelHead"
                    show-overflow
                    header-align="center"
                    :align="getAlign(item)"
                >
                    <!-- 自定义表头 -->
                    <template #header="{ column }">
                        <!-- 正常数据 -->
                        {{ item.name }}
                        <!-- <i v-if="item.search" class="el-icon-search head-icon"></i> -->
                    </template>

                    <!-- 搜索框式筛选 -->
                    <template #filter="{ $panel, column }" v-if="item.search">
                        <el-input
                            v-focus
                            class="my-input"
                            type="type"
                            v-for="(option, index) in column.filters"
                            :key="index"
                            v-model="option.data"
                            @input="$panel.changeOption($event, !!option.data, option)"
                        />
                    </template>

                    <!-- 自定义列模板 -->
                    <template slot-scope="scope">
                        <!-- 按钮 -->
                        <el-row v-if="item.type == 'btn'">
                            <el-tooltip placement="bottom" v-for="btn in item.btns" :key="btn.index" :disabled="btn.title === undefined">
                                <div slot="content">{{ btn.title }}</div>
                                <el-button
                                    :disabled="btn.hasOwnProperty('isDisabled') ? btn.isDisabled(scope.row) : false"
                                    :type="btn.type"
                                    :icon="btn.icon"
                                    size="mini"
                                    :v-authCode="authCode"
                                    @click.stop="handleBtn(btn.title, scope.rowIndex)"
                                ></el-button>
                            </el-tooltip>
                        </el-row>
                        <!-- 勾稽规则结果列表详情按钮事件 -->
                        <el-row v-if="item.type == 'detailsBtn'">
                            <el-tooltip placement="bottom" v-for="btn in item.btns" :key="btn.index" :disabled="btn.title === undefined">
                                <div slot="content">{{ btn.title }}</div>
                                <el-button
                                    :disabled="data[scope.rowIndex].ruleType === '9' && data[scope.rowIndex].relationType === '3' ? false : true"
                                    :type="btn.type"
                                    :icon="btn.icon"
                                    size="mini"
                                    @click.stop="handleDetailsBtn(btn.title, scope.rowIndex)"
                                ></el-button>
                            </el-tooltip>
                        </el-row>
                        <!-- 序号 -->
                        <el-row v-else-if="item.type == 'index'">
                            {{ scope.$rowIndex + pages.pageSize * (pages.currentPage - 1) + 1 }}
                        </el-row>
                        <!-- 状态标签 -->
                        <el-row v-else-if="item.type == 'statusTag'">
                            <status-tag v-if="scope.row[item.val]" :code="scope.row[item.val]" />
                        </el-row>
                        <!-- 分支标签 -->
                        <el-row v-else-if="item.type == 'branchTag'">
                            <branch-tag :data="scope.row[item.val]" />
                        </el-row>
                        <!-- 图片 -->
                        <el-row v-else-if="item.type == 'img'">
                            <img :src="scope.row[item.val]" :style="{ width: item.imgWidth, height: item.imgHeight }" />
                        </el-row>
                        <!-- 状态（根据key匹配文字） -->
                        <el-row v-else-if="item.type == 'status'">
                            {{ item.statusKV[scope.row[item.val]] }}
                        </el-row>
                        <!-- 输入框 -->
                        <el-row v-else-if="item.type == 'input'">
                            <el-input v-model="scope.row[item.val]" size="mini"></el-input>
                        </el-row>
                        <!-- 数字输入框 -->
                        <el-row v-else-if="item.type == 'numberInput'">
                            <el-input-number
                                v-model="scope.row[item.val]"
                                :precision="2"
                                :min="0"
                                controls-position="right"
                                size="mini"
                            ></el-input-number>
                        </el-row>
                        <!-- 方法操作 -->
                        <span v-else-if="item.type === 'func'">
                            {{ item.funcBody(scope.row[item.val], scope.row, item.val) || '--' }}
                        </span>
                        <!-- 日期 -->
                        <span v-else-if="item.type === 'funcTime'" style="display: block; text-align: center">
                            {{ item.funcBody(scope.row[item.val], scope.row, item.val) || '--' }}
                        </span>
                        <!-- 日期处理 -->
                        <span v-else-if="item.type === 'date'">
                            {{ dateFormat(scope.row[item.val]) || '--' }}
                        </span>
                        <span v-else-if="item.type === 'dates'">
                            {{ dateFormat(scope.row[item.val]) || '--' }} {{ timeFormat(scope.row['createTime']) }}
                        </span>
                        <!-- 时间处理 -->
                        <span v-else-if="item.type === 'time'">
                            {{ timeFormat(scope.row[item.val]) || '--' }}
                        </span>
                        <!-- 数值型 -->
                        <span v-else-if="item.type === 'funcNumber'" style="float: right">
                            {{ item.funcBody(scope.row[item.val], scope.row, item.val) || '--' }}
                        </span>
                        <!-- <span v-else-if="item.type === 'details'">
                            <el-button>查看</el-button>
                        </span> -->
                        <!-- 正常数据 -->
                        <span v-else>
                            {{
                                scope.row[item.val || item.prop] === 0 ||
                                (scope.row[item.val || item.prop] && (scope.row[item.val || item.prop] + '').trim())
                                    ? scope.row[item.val || item.prop]
                                    : '--'
                            }}
                            <!-- {{ scope.row[item.val || item.prop] }} -->
                        </span>
                    </template>
                </vxe-column>

                <!-- 空数据 -->
                <!-- <template #empty>
                    <img src="/vxe-table/static/other/img2.gif" />
                    <p>暂无数据</p>
                </template> -->
                <!-- <yh-column fixed="right" :width="1" label=" "></yh-column> -->
            </vxe-table>
        </div>
        <div class="pagination" v-if="!msg.hidePage && !symbol">
            <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                layout="total, prev, pager, next"
                :current-page="pages.currentPage"
                :page-size="pages.pageSize"
                :total="msg.returnData.total"
            >
            </el-pagination>
        </div>

        <div class="pagination" v-if="!msg.hidePage && symbol">
            <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-sizes="[5, 10, 20, 25, 50, 100, 300, 500]"
                layout="total, sizes, prev, pager, next, jumper"
                :current-page="pages.currentPage"
                :page-size="pages.pageSize"
                :total="msg.returnData.total"
            >
            </el-pagination>
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import BranchTag from '@/pages/risk-measure/components/branch-tag.vue';
import VXETable from 'vxe-table';
import { dateFormat, numberFormat, timeFormat } from '@/utils/tools';

// 创建一个简单的输入框筛选
VXETable.renderer.add('FilterInput', {
    // 筛选模板
    // renderFilter(h, renderOpts, params) {
    //     return [`<filter-input params=${params}></filter-input>`];
    // },
    // 重置数据方法
    filterResetMethod({ options }) {
        options.forEach(option => {
            option.data = '';
        });
    },
    // 重置筛选复原方法（当未点击确认时，该选项将被恢复为默认值）
    filterRecoverMethod({ option }) {
        option.data = '';
    },
    // 筛选方法
    filterMethod({ option, row, column }) {
        console.log('@!!@!@');

        const { data } = option;
        const cellValue = row[column.property];
        if (cellValue) {
            return cellValue.indexOf(data) > -1;
        }
        return false;
    },
});
// 筛选指令获取焦点
Vue.directive('focus', {
    inserted(el, binding, vnode) {
        el.querySelector('input').focus();
    },
});

@Component({ name: 'RiskTable', components: { StatusTag, BranchTag } })
export default class RiskTable extends Vue {
    dateFormat = dateFormat;
    timeFormat = timeFormat;
    // 主键
    @Prop() msg: any;

    @Prop() nameType: any;

    @Prop() symbol: boolean;

    private data = {};

    private title: any = {};

    @Prop({
        type: Object,
        default: () => {
            return { currentPage: 1, pageSize: 25, total: 0 };
        },
    })
    pages;
    // 分页
    // private pages = { currentPage: 1, pageSize: 25 };

    // 选择当前页或所有页
    private pageType: string = '0';

    // 图标dom
    private iconDom: any = null;
    keyIndex: number = 0;

    @Watch('msg', { immediate: true, deep: true })
    watchTableData(newData) {
        this.msg = newData;
        console.log('changeTable');

        this.changeData();
        // this.keyIndex++;
    }

    @Watch('nameType', { immediate: true, deep: true })
    watchNameType(newData) {
        this.nameType = newData;
    }

    // 重新渲染表格
    changeData() {
        this.data = this.msg.returnData[this.msg.dataKey];
        let title = this.msg.title;
        // 插入序号
        let index = [{ en: true, name: '序号', type: 'index', width: '50' }];
        let newTitle = title;
        // 处理数据(加宽)
        for (let i in newTitle) {
            if (newTitle[i].type == 'btn' && !newTitle[i].width && !newTitle[i].auto && !newTitle[i].minWidth) {
                newTitle[i].width = 180;
            }
        }
        this.title = newTitle;

        this.$nextTick(() => {
            let arr = [];
            for (let i = 0; i < title.length; i++) {
                const element = title[i];
                if (element.filters) {
                    arr.push(element);
                }
            }

            // if (!this.iconDom) {
            //     // let obj = document.querySelector('#risk-table');
            //     // console.log(obj);

            //     // this.iconDom = obj.querySelectorAll('.vxe-icon--funnel');
            //     this.iconDom = document.querySelectorAll('.vxe-icon--funnel');
            //     for (let i = 0; i < this.iconDom.length; i++) {
            //         arr.forEach((ele, index) => {
            //             if (ele.search) {
            //                 this.iconDom[index].className = 'vxe-filter--btn el-icon-search';
            //             }
            //         });
            //     }
            // }
        });
    }

    // 单元格样式
    cellStyle({ row, column, rowIndex, columnIndex }) {
        // 颜色
        if (column.property && column.property.indexOf('Color') >= 1) {
            // 判断是否需要渲染样式
            if (row[column.property]) {
                return { color: row[column.property] };
            }
        }
    }

    /**
     * 凡不为数值/图标/输入文本框/拉选框/展示框的内容都左对齐
     * 数值右对齐
     * /图标/输入文本框/展示框、日期、时间、枚举值居中对齐
     */
    getAlign(ele: any) {
        let obj = this.title.find(item => item.val == ele.val);
        return (obj && obj.align) || 'left';
    }

    // 表头渲染
    labelHead(h, { column, index }) {
        let l = column.label.length;
        let f = 14; // 每个字大小，其实是每个字的比例值，大概会比字体大小差不多大一点，
        column.minWidth = f * l + 25; // 字大小乘个数即长度 ,注意不要加px像素，这里minWidth只是一个比例值，不是真正的长度
        // 然后将列标题放在一个div块中，注意块的宽度一定要100%，否则表格显示不完全
        return h('div', { class: 'table-head', style: { width: '100%' } }, [column.label]);
    }

    // 表格列筛选数据
    filterHandler({ option, row, column }) {
        console.log(' ?? , 1212');

        const property = column['property'];
        return row[property].includes(option.data);
    }

    // 表格列下拉筛选
    filterTypeSelect({ value, row, column }) {
        // console.log(value, row, column);
        return row[column.property] == value;
    }

    // 单行单击事件
    handleRow(row, event, column) {
        this.$emit('handleRow', row);
    }

    // 单行双击事件
    handleDbRow(row, column, event) {
        this.$emit('handleDbRow', row);
    }

    // 按钮点击事件
    handleBtn(type, rowIndex) {
        this.$emit('handleBtn', { type: type, row: JSON.parse(JSON.stringify(this.data[rowIndex])) });
    }
    // 勾稽规则结果列表详情按钮事件
    handleDetailsBtn(type, rowIndex) {
        this.$emit('handleDetailsBtn', { type: type, row: JSON.parse(JSON.stringify(this.data[rowIndex])) });
    }

    // 表格勾选事件
    handleChecked(selection, event, row) {
        console.log(event);
        this.$emit('handleChecked', selection, this.pageType);
    }

    // 勾选全选事件
    handleCheckedAll(selection) {
        this.$emit('handleChecked', selection, this.pageType);
    }

    // 筛选事件
    handleFilter({ column, property, values, datas, filterList, $event }) {
        this.$emit('handleFilter', filterList);
    }

    // 排序事件
    handleSort({ column, property, order, sortBy, sortList, $event }) {
        this.$emit('handleSort', property, order);
    }

    // 页码改动事件
    handleSizeChange(val) {
        this.pages.pageSize = val;
        this.$emit('getList', this.pages);
    }

    // 页数改动事件
    handleCurrentChange(val) {
        this.pages.currentPage = val;
        this.$emit('getList', this.pages);
    }

    // test
    handleCommand(command) {
        this.pageType = command;
        (this.$refs.riskTable as any).clearCheckboxRow();
        (this.$refs.riskTable as any).toggleAllCheckboxRow();
    }

    sumNum(list, field) {
        let count = 0;
        list.forEach(item => {
            count += Number(item[field] || '');
        });
        return numberFormat(count, 2);
    }

    footerMethod({ columns, data }) {
        const footerData = [
            columns.map((column, _columnIndex) => {
                if (this.msg.footerColumns.includes(column.property)) {
                    return this.sumNum(data, this.msg.footerColumns);
                }
                return '--';
            }),
        ];
        return footerData;
    }
}
</script>

<style lang="scss" scoped>
#risk-table {
    .table-box {
        position: relative;
        tbody {
            .el-button {
                padding: 0;
            }

            .el-button--mini {
                padding: 2px 8px;
            }
        }
        .head-icon {
            position: absolute;
            right: 9px;
            top: 11px;
        }
        .head-icon:hover {
            color: #d43131;
        }
        .el-icon-arrow-down:hover {
            color: #d43131;
        }
    }
    .my-input {
        margin: 10px;
        width: 150px;
    }
}
/deep/ .vxe-table {
    .vxe-body--column .vxe-cell {
        text-align: center;
    }
    .vxe-table--main-wrapper {
        height: 100%;
    }
    .vxe-table--body-wrapper.body--wrapper {
        height: calc(100% - 36px);
    }
}

/deep/ .el-pagination .el-select .el-input .el-input__inner {
    background: #fff;
    border: 1px solid #dcdfe6;
}
</style>
